package com.wisezone.studentmanger.listener;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.wisezone.studentmanger.model.UserMessage;
import com.wisezone.studentmanger.util.Utils;

@WebListener
public class UserCountHttpSessionListener implements HttpSessionListener {
	public static int userCount; //存储在线用户数
	
    public void sessionCreated(HttpSessionEvent arg0)  { 
    	userCount++;
    	ServletContext servletContext = arg0.getSession().getServletContext();
    	servletContext.setAttribute("USER_COUNT", userCount);
    	System.out.println("sessionCreated "+userCount);
    }

    public void sessionDestroyed(HttpSessionEvent arg0)  { 
        userCount--;
    	ServletContext servletContext = arg0.getSession().getServletContext();
    	servletContext.setAttribute("USER_COUNT", userCount);
    	System.out.println("sessionDestroyed "+userCount);
    	
    	List<UserMessage> userLists = (List<UserMessage>) servletContext.getAttribute("USER_LISTS");
    	String sessionId = arg0.getSession().getId();
    	UserMessage user = Utils.getUserMessageByList(userLists, sessionId);
    	if(user != null){
    		userLists.remove(user);
    	}
    	
    	//servletContext.setAttribute("USER_LISTS", userLists);
    }
	
}
